<?php


namespace app\controller\admin;


use app\BaseController;
use app\models\goods\ProductModel;
use app\models\user\DetailedIntegralModel;
use app\models\user\DetailedMoneyModel;
use app\models\user\PromotionRewardsModel;
use app\models\user\UserModel;
use app\models\user\UserWithdrawModel;
use app\services\user\DetailIntegralService;
use app\services\user\DetailMoneyService;
use think\facade\Db;

class FinanceController extends BaseAdminController
{
    function setSearch()
    {
        return [
            'like' => ['order_sn'],
            '=' => ['status', 'type'],
        ];
    }

    function setSort()
    {
        return [
            'user_name' => 'user_id',
            'mobile' => 'user_id',
        ];
    }

    /**
     * 提现记录
     * @return \think\response\Json
     */
    public function getWithdrawList()
    {
        try {
            $where = $this->searchWhere;
            $list = UserWithdrawModel::where($where)
                ->order($this->orderBy, $this->sort)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$value) {
                $userInfo = UserModel::find($value['user_id']);
                $value['user_name'] = $userInfo['nick'] ?? '';
                $value['mobile'] = $userInfo['mobile'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    public function getBalanceType()
    {
        try {
            $list = DetailMoneyService::getTypeArr();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 余额变动记录
     * @return \think\response\Json
     */
    public function getBalanceList()
    {
        try {
            $where = [];
            $mobile = $this->request->param('mobile', '', 'trim');
            if ($mobile) {
                $userId = UserModel::where('mobile', $mobile)->value('id');
                $where[] = ['user_id', '=', $userId];
            }
            $orderSn = $this->request->param('order_sn', '', 'trim');
            if ($orderSn) {
                $where[] = ['order_sn', '=', $orderSn];
            }
            $type = $this->request->param('type', '', 'trim');
            if ($type) {
                $where[] = ['type', '=', $type];
            }
            $list = DetailedMoneyModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = UserModel::find($v['user_id']);
                $v['nick'] = $userInfo['nick'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getIntegralType()
    {
        try {
            $list = DetailIntegralService::getTypeArr();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 积分变动记录
     * @return \think\response\Json
     */
    public function getIntegralList()
    {
        try {
            $where = [];
            $mobile = $this->request->param('mobile', '', 'trim');
            if ($mobile) {
                $userId = UserModel::where('mobile', $mobile)->value('id');
                $where[] = ['user_id', '=', $userId];
            }
            $orderSn = $this->request->param('order_sn', '', 'trim');
            if ($orderSn) {
                $where[] = ['order_sn', '=', $orderSn];
            }
            $type = $this->request->param('type', '', 'trim');
            if ($type) {
                $where[] = ['type', '=', $type];
            }
            $list = DetailedIntegralModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = UserModel::find($v['user_id']);
                $v['nick'] = $userInfo['nick'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 申请推荐奖励记录
     * @return \think\response\Json
     */
    public function getPromotionRewardsList()
    {
        try {
            $where = [];
            $name = $this->request->param('user_name', '', 'trim');
            if ($name) {
                $userIdArr = UserModel::where('nick|mobile', 'like', '%' . $name . '%')->column('id');
                $where[] = ['user_id', 'in', $userIdArr];
            }
            $type = $this->request->param('type', '', 'trim');
            if ($type) {
                $where[] = ['type', '=', $type];
            }
            $status = $this->request->param('status', '', 'trim');
            if ($status != "") {
                $where[] = ['status', '=', $status];
            }
            $startTime = $this->request->param('start_time', '', 'trim');
            if ($startTime) {
                $where[] = ['create_time', '>=', strtotime($startTime)];
            }
            $endTime = $this->request->param('end_time', '', 'trim');
            if ($endTime) {
                $where[] = ['create_time', '<=', strtotime($endTime)];
            }

            $list = PromotionRewardsModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = UserModel::find($v['user_id']);
                $v['user_name'] = $userInfo['nick'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? "";

                $effective = json_decode($v['effective'],true);

                $v['number'] = $effective[$v['accumulated_rewards']]['num'];
                $v['rewards'] = $effective[$v['accumulated_rewards']]['title'];
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 团队详情
     * @return \think\response\Json
     */
    public function getTeamList()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0);
            $info = PromotionRewardsModel::find($id);
            if (!$info) {
                throw new \Exception('推广申请未找到');
            }
            if($info['status'] == 1){
                $userList = UserModel::where('id','in',$info['final_ids'])->select()->toArray();
            }else{
                $userList = UserModel::where('id','in',$info['promote_ids'])->select()->toArray();
            }
            Db::commit();
            return $this->success($userList);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 直推奖励审核
     * @return \think\response\Json
     */
    public function audit()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status'); //状态： 1=已审核
            $handle = $this->request->param('handle'); //状态：0=全部清除, 1=按照活动人数清除
            $reason = $this->request->param('reason', '', 'trim');
            $info = PromotionRewardsModel::find($id);
            if (!$info) {
                throw new \Exception("申请奖励记录不存在");
            }
            if ($info['status'] != 0) {
                throw new \Exception("提现已审核");
            }
            $info->status = $status;
            $info->remark = $reason;
            $info->audit_time = time();
            $info->update_time = time();
            $info->handle = $handle;

            //按照奖励人数
            $effective = json_decode($info['effective'],true);

            if($handle == 1){
                //按照注册时间清楚固定人数
                $promote_ids = explode(',',$info->promote_ids);
                $output_array = array_slice($promote_ids, 0, $effective[$info['accumulated_rewards']]['num']);
                $result_ids = array_diff($promote_ids, $output_array);
                $info->final_ids = implode(',',$output_array);
            }else{
                //全部清楚
                $promote_ids = $info->promote_ids;
                $result_ids = $info->promote_ids;
                $info->final_ids = $info->promote_ids;
            }
            $info->save();

            Db::name('user')->where('id','in',$promote_ids)->update(['is_reward' => 1]);
            if(!empty($result_ids)){
                Db::name('user')->where('id','in',$result_ids)->update(['is_reward' => 0]);
            }

//            if($info->label == 1){
//                Db::name('user')->where('inviter',$info->user_id)->update(['is_reward' => 1]);
//            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

}